#include "poly.h"

#include <cstdio>
#include <cstdlib>


Status PolyInsert(PolyNomial &L, PolyNode *s) {
    if (!L) {
        L = s;
        s->next = NULL;
        return OK;
    }

    PolyNomial p = L;
    PolyNomial prev = NULL;

    while (p && p->expn < s->expn) {
        prev = p;
        p = p->next;
    }

    if (p && p->expn == s->expn) {
        p->coef += s->coef;
        free(s);
        if (p->coef == 0) {
            if (prev) {
                prev->next = p->next;
            } else {
                L = p->next;
            }
            free(p);
        }
    } else {
        if (prev) {
            prev->next = s;
        } else {
            L = s;
        }
        s->next = p;
    }

    return OK;
}


Status CreatPolynList(PolyNomial &L, int n) {
    L = NULL;
    for (int i = 0; i < n; i++) {
        PolyNode *s = (PolyNode *) malloc(sizeof(PolyNode));
        if (!s) return ERROR;

        printf("Enter coefficient and exponent for term %d: ", i + 1);
        scanf("%f %d", &(s->coef), &(s->expn));

        PolyInsert(L, s);
    }
    return OK;
}

Status PolyAdd(PolyNomial &La, PolyNomial Lb) {
    PolyNomial p = Lb;
    while (p) {
        PolyNode *temp = p;
        p = p->next;

        PolyNode *s = (PolyNode *) malloc(sizeof(PolyNode));
        if (!s) return ERROR;

        s->coef = temp->coef;
        s->expn = temp->expn;

        PolyInsert(La, s);
    }
    return OK;
}


void DisplayPoly(PolyNomial L) {
    if (!L) {
        printf("0\n");
        return;
    }

    PolyNomial p = L;
    int firstTerm = 1;

    while (p) {
        if (!firstTerm) {
            if (p->coef >= 0) {
                printf("+");
            }
        }

        if (p->expn == 0) {
            printf("%.2f", p->coef);
        } else {
            printf("%.2f*x^%d", p->coef, p->expn);
        }

        firstTerm = 0;
        p = p->next;
    }
    printf("\n");
}
